<div class="easyui-layout" data-options="fit:true">
	<div data-options="region:'north'" style="height:40px">
		<div style="width:340px;padding: 6px 0 0 5px;padding: 8px 0 0 5px\d;float:left;">
			奖助学金：<select id="scholarshipType" class="select" style="width:110px"></select>
			等级：<select id="scholarshipLevel" class="select" style="width:110px"></select>
		</div>
		<div style="float:left;padding:5px 0 0 5px;">
			<a href="javascript:void(0)" onclick="$('#conditionWin').window('open');" class="easyui-linkbutton" data-options="iconCls:'icon-search'">筛选学生</a>
			<span style="margin-left:20px;height:20px;">当前筛选条件：</span>
			<span id="currentCondition" style="display:inline-block;vertical-align:sub;color:red;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;width:250px;">全部学生</span>
		</div>
	</div>
    <div data-options="region:'west',split:true" style="width:480px;">
    	<table class="easyui-datagrid" id="studentList"  
    		data-options="url:'user/students',fit:true,fitColumns:true,rownumbers:true,pagination:true,pageSize:20,pageList:[20,50,100,200,500,1000],
    			toolbar:leftToolbar,rowStyler:stuRowStyler,loadFilter:freeStuRender,onLoadSuccess:diableCheckbox,onClickRow:disableClickRow,onCheckAll:checkPart">
    		<thead>
		        <tr>
		        	<th data-options="field:'ck',checkbox:true"></th>
		            <th data-options="field:'xm',halign:'center',width:60">姓名</th>
		            <th data-options="field:'lqyxsmc',halign:'center',width:120">所在系</th>
		            <th data-options="field:'cwbh',align:'center',width:80">财务编号</th>
		            <th data-options="field:'lqzymc',halign:'center',width:130">主修专业</th>
		            <th data-options="field:'xh',halign:'center',width:60">学号</th>
		        </tr>
		    </thead>
    	</table>
    </div>
    <div data-options="region:'center'">
    	<div class="easyui-layout" data-options="fit:true">
    		<div data-options="region:'center'">
    			<table class="easyui-datagrid" id="selectedStudents" data-options="fit:true,fitColumns:true,rownumbers:true,toolbar:rightToolbar">
		    		<thead>
				        <tr>
				        	<th data-options="field:'ck',checkbox:true"></th>
				            <th data-options="field:'xm',width:$(this).width() * 0.1,halign:'center'">姓名</th>
				            <th data-options="field:'lqyxsmc',width:$(this).width() * 0.2,halign:'center'">所在系</th>
				            <th data-options="field:'cwbh',align:'center',width:$(this).width() * 0.15">财务编号</th>
				            <th data-options="field:'lqzymc',width:$(this).width() * 0.2,halign:'center'">主修专业</th>
				            <th data-options="field:'scholarshipName',width:$(this).width() * 0.15,halign:'center'">奖助学金</th>
				            <th data-options="field:'levelName',width:$(this).width() * 0.1,halign:'center'">等级</th>
				            <th data-options="field:'scholarshipMoney',width:$(this).width() * 0.1,halign:'center'">奖金</th>
				        </tr>
				    </thead>
		    	</table>
    		</div>
    		<div data-options="region:'south'" style="height:40px">
    			<span style="float:right;margin:5px 15px 0 0;">
    				<a href="javascript:void()" onclick="showPreviewWin();" class="easyui-linkbutton" data-options="iconCls:'icon-excel'">预览发放</a>
    			</span>
    		</div>
    	</div>
    </div>
</div>

<div id="conditionWin" class="easyui-window" title="请选择学生的筛选条件" style="width:460px;height:380px;padding-left:30px;padding-top:20px;"
        data-options="iconCls:'icon-save',modal:true,closed:true,minimizable:false,collapsible:false,maximizable:false">
        <table class="form_table" style="border:0px;">
        	<tr><td>系别：</td><td><input class="easyui-combobox" id="college" style="width:240px;" value="-"
            data-options="multiple:true,url:'uni/colleges',valueField:'lqyxsm',textField:'lqyxsmc',onSelect:checkIfAll,onHidePanel:cascadeMajor
            	,loadFilter:function(data){return _.union([{id:0,lqyxsm:'-',lqyxsmc: '不限'}],data);}"></td></tr>
            <tr><td>专业：</td><td><input class="easyui-combobox" id="major" style="width:240px;" value="-" 
            data-options="multiple:true,url:'uni/majors',valueField:'lqzydm',textField:'lqzymc',onSelect:checkIfAll
            	,loadFilter:function(data){return _.union([{id:0,lqzydm:'-',lqzymc: '不限'}],data);}"></td></tr>
            <tr><td>年级：</td><td><input class="easyui-combobox" id="year" style="width:240px;" value="-" 
            data-options="multiple:true,url:'grant/years',valueField:'id',textField:'value',panelHeight:110,onSelect:checkIfAll
            	,loadFilter:function(data){return _.union([{id:'-',value: '不限'}],data);}"></td></tr>
            <tr><td>类别：</td><td><input class="easyui-combobox" id="classify" style="width:240px;" value="-" 
            data-options="multiple:true,url:'grant/classify',valueField:'id',textField:'value',panelHeight:110,onSelect:checkIfAll
            	,loadFilter:function(data){return _.union([{id:'-',value: '不限'}],data);}"></td></tr>
            <tr><td>所属名单：</td><td><input class="easyui-combobox" id="groupId" style="width:240px;" value="-" 
            data-options="multiple:true,url:'user/group',valueField:'id',textField:'name',panelHeight:110,onSelect:checkIfAll
            	,loadFilter:function(data){return _.union([{id:'-',name: '不限'}],data);}"></td></tr>
            <tr><td></td><td><a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-search'" onclick="refreshStudents()">确定</a>
            	<a href="javascript:void(0)" class="easyui-linkbutton" data-options="iconCls:'icon-no'" onclick="$('#conditionWin').window('close');">取消</a></td></tr>
        </table>
</div>

<div id="previewWin" class="easyui-window" title="<span>预览</span><span style='margin-left:160px;color:red;font-weight:normal;'>注意：点击导出/发放按钮就会记录一次发放。</span>" style="width:700px;height:500px"
        data-options="iconCls:'icon-save',modal:true,closed:true,minimizable:false,collapsible:false,maximizable:false">
    <div class="easyui-layout" data-options="fit:true">
        <div data-options="region:'north',split:true" style="height:100px">
        	<div class="easyui-layout" data-options="fit:true">
        		<div data-options="region:'center'">
        	<div class="easyui-layout" data-options="fit:true">
        		<div data-options="region:'center'">
选择输出列：<br/>
<input type="checkbox" checked="checked" name="columns" value="lqyxsmc">系名称&nbsp;
<input type="checkbox" checked="checked" name="columns" value="xh">学号&nbsp;
<input type="checkbox" checked="checked" name="columns" value="xm">姓名&nbsp;
<input type="checkbox" checked="checked" name="columns" value="xb">性别&nbsp;
<input type="checkbox" checked="checked" name="columns" value="lqzymc">专业&nbsp;
<input type="checkbox" checked="checked" name="columns" value="lqlbmc">录取类别&nbsp;
<input type="checkbox" checked="checked" name="columns" value="cwbh">财务编号&nbsp;<br/>
<input type="checkbox" checked="checked" name="columns" value="scholarshipName">奖助学金&nbsp;
<input type="checkbox" checked="checked" name="columns" value="levelName">等级&nbsp;
<input type="checkbox" checked="checked" name="columns" value="scholarshipMoney">金额&nbsp;
<input type="checkbox" checked="checked" name="columns" value="memo">备注&nbsp;
				</div>
        		<div data-options="region:'south'" style="height:30px;">
        		标题：<input type="text" id="title" style="width:300px;" value="默认标题">
        		</div>
        	</div>
        	</div>
        		<div data-options="region:'east'" style="width:160px;">
        			<span style="float:right;margin:3px 20px 0 0;">
<a href="javascript:void(0)" onclick="doPreview();" class="easyui-linkbutton" data-options="iconCls:'icon-excel'">预览</a>
					</span>
        			<span style="float:right;margin:3px 20px 0 0;">
<a href="javascript:void(0)" onclick="checkAdminPwd();" class="easyui-linkbutton" data-options="iconCls:'icon-excel'">发放</a>
					</span>
					<span style="float:right;margin:3px 20px 0 0;">
<a href="javascript:void(0)" onclick="$('#previewWin').window('close');" class="easyui-linkbutton" data-options="iconCls:'icon-no'">关闭</a>
					</span>
        		</div>
        	</div>
        </div>
        <div data-options="region:'center'">
		   <img id="previewImg" alt="" src="">
        </div>
    </div>
</div>
<script type="text/javascript" src="statics/js/xdate.js"></script>
<!-- <script type="text/javascript" src="statics/js/scholarship/effect.js"></script> -->
<script>

$(function() {
	 $('#scholarshipType').change(function(){
		changeLevels($('#scholarshipType').val());
		$('#studentList').datagrid('reload');
	});
	
	$.ajax({
		url:'uni/useableScholars',
		success:function(scholarshipTypes) {
			//获取第一个奖助学金的档次
			var selected = false,selectedId;

			//显示奖助学金列表
			var options = $.map(scholarshipTypes,function(row) {
				var granted = row.frequency > 0 && !!row.lastGrant && new XDate(row.lastGrant).diffMonths(new XDate()) < row.frequency;
				if(!selected && !granted) {changeLevels(row.id);selected = true;selectedId = row.id;}
				return '<option value="' + row.id + '" ' + (granted ? 'granted="true"':'') + '>' + row.name + (granted ? '[本次已发放]' : '') + '</option>';
			}).join('');
			$('#scholarshipType').html(options);
			
			if(selected) {
				$('#scholarshipType').val(selectedId);
			} else {
				$.messager.alert('提示','本月所有奖学金均已发放！');
				$('#tt').tabs('close','奖助学金发放');
			}
		}
	});

	function changeLevels(scholarshipId) {
		$.ajax({url:'uni/scholarLevels/' + scholarshipId,success:function(levels){
			//刷新档次列表
			var lvlOpts = $.map(levels,function(row) {
				return '<option value="' + row.id + '" money="' + row.money + '" name="' + row.name + '">' + row.name + '(￥' + row.money + ')</option>';
			}).join('');
			$('#scholarshipLevel').html(lvlOpts);
		}});
	}
})

var xhs = new Array();
var leftToolbar = [{
    text:'预选',
    iconCls:'icon-add',
    handler:function(){
        var checkedList = $('#studentList').datagrid('getChecked');
        if(checkedList.length == 0) {
			$.messager.alert('提示','请至少选择一个学生！');
			return;
        }
        $.each(checkedList,function(id,row) {
            if($.inArray(row.xh,xhs) > -1) return;
            row.scholarshipName = $('#scholarshipType > option:selected').text();//奖助学金名称
            row.levelName = $('#scholarshipLevel > option:selected').attr('name');//奖助学金等级名称
            row.scholarshipMoney = $('#scholarshipLevel > option:selected').attr('money');//奖金
            row.scholarshipId = $('#scholarshipType').val();
            row.scholarshipLevel = $('#scholarshipLevel').val();
        	$('#selectedStudents').datagrid('appendRow',row);
        	xhs.push(row.xh);
        });
    }
}];
var rightToolbar = [{
    text:'剔除',
    iconCls:'icon-remove',
    handler:function(){
        var dg = $('#selectedStudents');
        var checkedList = dg.datagrid('getChecked');
        if(checkedList.length == 0) {
        	$.messager.alert('提示','请至少选择一个学生！');
			return;
        }
        $.each(dg.datagrid('getChecked'),function(id,row) {
        	dg.datagrid('deleteRow',dg.datagrid('getRowIndex',row));
        	xhs = _.without(xhs,row.xh);
        	//xhs.slice($.inArray(row.xh,xhs), 1);//I don't know why wrong.
        });
    }
}];

function showPreviewWin() {
	if($('#selectedStudents').datagrid('getRows').length == 0) {
		$.messager.alert('提示','请至少选择一个学生！');
		return;
	} 

	$('#title').val($('#scholarshipType :selected').html() + "发放表(" + new XDate().toString('yyyy-MM-dd') + ")" );
	$('#previewWin').window('open');
	doPreview();
}

function doPreview() {
	$.ajax({
		url:'export',
		data:"data=" + JSON.stringify($('#selectedStudents').datagrid('getRows')) + 
			"&title=" + $('#title').val() + 
			"&columns=" + _.uniq($.map($('input[name=columns]:checked'),function(row){return $(row).val()})).join(','),
		type:'POST',
		success:function(html) {
			$('#previewImg').attr("src",'export/preview?v=' + new Date());
		}
	});
	
}

function checkAdminPwd() {
	$.messager.prompt('提示','请输入管理密码！',function(r) {
		if(r) {
			$.ajax({
				url:'user/info?v=' + new Date(),
				success:function(info) {
					console.log(r);
					if(info.userType == 2 && info.user.managePwd == r) {
						doExport();return;
					}

					$.messager.alert('提示','您输入的密码有误！');
				}
			});
		}
	});
}

function doExport() {
	window.location.href = 'export/excel?v=' + new Date();
	$('#previewWin').window('close');
}

function checkIfAll(record) {
	if(record[$(this).combobox('options').valueField] == '-') {
		$(this).combobox('setValue','-');
	} else {
		$(this).combobox('unselect','-');
	}
}

function cascadeMajor() {
	var college = $('#college').combobox('getValues').join(',');
	$('#major').combobox('reload','uni/majors' + (college == '-'? '':'?college=' + college));
}

function refreshStudents() {
	var info = '学院:' + $('#college').combobox('getText') + ',' +
			'专业:' + $('#major').combobox('getText') + ',' +
			'年级:' + $('#year').combobox('getText') + ',' +
			'类别:' + $('#classify').combobox('getText') + ',' +
			'所属名单:' + $('#groupId').combobox('getText');
	$('#currentCondition').html(info);
	$('#currentCondition').attr('title',info);

	$('#studentList').datagrid('reload',
		{college:$('#college').combobox('getValues').join(','),
		major:$('#major').combobox('getValues').join(','),
		year:$('#year').combobox('getValues').join(','),
		classify:$('#classify').combobox('getValues').join(','),
		groupId:$('#groupId').combobox('getValues').join(','),});

	$('#conditionWin').window('close');
}

function stuRowStyler(index,row) {
	if(row.freeze) {return 'background-color:#F0F0F0;color:#979797;';}
}

function freeStuRender(data) {
	var freezeList = $.parseJSON($.ajax({url: "user/freezeList?scholarshipId=" + $('#scholarshipType').val(),async: false}).responseText);
	var freezeXhs = $.map(freezeList,function(row){return row.xh;});
	$.each(data.rows,function(id,row) {//标记冻结学生
		if($.inArray(row.xh,freezeXhs) > -1) {row.freeze = true;row.xm = row.xm + '[已冻结]';}
	});
	return data;
}

function diableCheckbox(data) {
	if (data.rows.length > 0) {
        //循环判断操作为新增的不能选择
        for (var i = 0; i < data.rows.length; i++) {
            //根据operate让某些行不可选
            if (data.rows[i].freeze) {
                $("input[type='checkbox']")[i + 1].disabled = true;
            }
        }
    }
}

function disableClickRow(rowIndex, rowData){
    //加载完毕后获取所有的checkbox遍历
    $("input[type='checkbox']").each(function(index, el){
        //如果当前的复选框不可选，则不让其选中
        if (el.disabled == true) $('#studentList').datagrid('unselectRow', index - 1);
    })
}

function checkPart(rows) {
	$.each(rows,function(index,row) {
		if (row.freeze == true) {
			$('#studentList').datagrid('unselectRow', index);
		}
	});
	$('#studentList').datagrid('getPanel').find('.datagrid-header-check input').prop('checked',true);
}
</script>